#include "effect.h"
#include <math.h>
#include <stdlib.h>

long dodo_vibrato(double low_freq, double depth, smpl_t *buf, long buf_size)
{
        long i;
        long extend_size = (long) depth + 1 + 1; //first 1 for the loss in (long) cast, second 1 for not to override the right one.

        double lfo_circle = SAMPLE_RATE / low_freq;

        //reverse, to make every orig sample safe before they are out of use.
        for(i = buf_size + extend_size -1; i >= extend_size; --i)
        {
                double shift = (sin(i / lfo_circle * 2.0 * M_PI) + 1.0) * 0.5 * depth;
                double temp_i;
                double weight = modf(shift, &temp_i);

                long left_i = i - extend_size + temp_i;
                long right_i = left_i + 1;

                buf[i] =(smpl_t) (buf[left_i] * (1 - weight) + buf[right_i] * weight);
        }

        for(i = 0; i < extend_size; ++i)
        {
                buf[i] = 0;
        }

        return buf_size + extend_size;
}

//It's almost a copy of dodo_vibrato(), we shall delete that later...
//should add a sweeping filter to it.
long dodo_vib_chorus(double low_freq, double depth, double dry_ratio, smpl_t *buf, long buf_size)
{
        long i;
        long extend_size = (long) depth + 1 ; //first 1 for the loss in (long) cast, no second 1 for not to override the right one.
        smpl_t *vib_buf = (smpl_t*) malloc ((buf_size + extend_size) * sizeof(smpl_t));

        double lfo_circle = SAMPLE_RATE / low_freq;

//make vib
        for(i = 0; i < extend_size; ++i)
        {
                vib_buf[i] = 0;
        }
        for(i = extend_size; i < buf_size + extend_size ; ++i)
        {
                double shift = (sin(i / lfo_circle * 2.0 * M_PI) + 1.0) * 0.5 * depth;
                double temp_i;
                double weight = modf(shift, &temp_i);

                long left_i = i - extend_size + temp_i;
                long right_i = left_i + 1;

                vib_buf[i] =(smpl_t) (buf[left_i] * (1 - weight) + buf[right_i] * weight);
        }

//add vib to original wave to make chorus
        for(i = 0; i < buf_size; ++i)
        {
                buf[i] = buf[i] * dry_ratio + vib_buf[i] * (1 - dry_ratio);
        }

        free(vib_buf);
        return buf_size; // + extend_size; //so, not extend it is also ok...
}
